<script setup lang="ts">
  import { HMessageBox } from '@/components/common/message'
  import { useGetGoodList } from '@/services/pages/good/useGood'
  import { nextTick, PropType, ref, watch } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import bomSelectModal from './bom-select-modal.vue'
  import { RefreshRight, Search } from '@element-plus/icons-vue'
  import { TableInstance } from 'element-plus'
  import useGoodBomChildListService from '@/services/module/product/useGoodBomChildListService'

  const { goodBomChildList, getGoodBomChildListLoading, getGoodBomChildList } =
    useGoodBomChildListService()
  const {
    goodList,
    goodListTotal,
    getGoodListParam,
    getGoodListLoading,
    getGoodList,
    resetGetGoodListParam,
  } = useGetGoodList()

  defineOptions({
    name: 'SparePartSelectModal',
  })

  const emits = defineEmits<{
    (
      e: 'update',
      value: { goodList: Array<GoodItem>; bomList: Array<GoodAPIResponse.GoodBomChildListItem> },
    ): void
  }>()

  const props = defineProps({
    goodSelection: {
      type: Array as PropType<Array<{ spareId: string; specId: string; isBom: boolean }>>,
      default: () => [],
    },
  })

  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const tableInstance = ref<TableInstance | null>(null)

  const visible = defineModel<boolean>('modelValue', { default: false })
  const bomSelectModalVisible = ref(false)

  const selection = ref<Array<GoodItem>>([])
  const bomSelection = ref<Array<GoodAPIResponse.GoodBomChildListItem>>([])

  const onResetClick = () => {
    resetGetGoodListParam()
    getGoodList()
  }

  const onBomQueryClick = async () => {
    if (selection.value.length <= 0) {
      HMessageBox.error('请选择要查询的商品')
      return
    }

    if (selection.value.length > 1) {
      HMessageBox.error('只能选择一条商品进行BOM查询')
      return
    }

    await getGoodBomChildList(selection.value[0].id)
    if (goodBomChildList.value.length <= 0) {
      HMessageBox.warning('该商品没有BOM')
      return
    }

    bomSelectModalVisible.value = true
  }

  const onCancelClick = () => {
    visible.value = false
  }

  const handleTableSelectionChange = (value: Array<GoodItem>) => {
    selection.value = value
  }

  const getList = async () => {
    if (paginationInstance.value) {
      getGoodListParam.value.page = paginationInstance.value.current
      getGoodListParam.value.limit = paginationInstance.value.size
      await getGoodList()

      goodList.value.forEach((good) => {
        props.goodSelection.forEach((goodSelection) => {
          if (
            good.id === goodSelection.spareId &&
            good.specId === goodSelection.specId &&
            !goodSelection.isBom
          ) {
            tableInstance.value && tableInstance.value.toggleRowSelection(good, true)
          }
        })
      })
    }
  }

  const onConfirmClick = () => {
    emits('update', {
      goodList: selection.value,
      bomList: bomSelection.value,
    })
    visible.value = false
  }

  const handleBomSelectModalUpdate = (bomList: Array<GoodAPIResponse.GoodBomChildListItem>) => {
    selection.value.length = 0
    bomSelection.value = bomList
    onConfirmClick()
  }

  watch(visible, (value) => {
    if (value) {
      nextTick(() => {
        getList()
      })
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1000"
    unit="px"
    :loading="getGoodListLoading"
    title="选择配件"
  >
    <div class="good-select-modal">
      <div class="header">
        <div class="title">配件列表</div>
        <div class="search">
          <el-select
            v-model="getGoodListParam.goodsType"
            style="width: 120px"
            placeholder="请选择分类"
            clearable
            @clear="getList"
            @change="getList"
          >
            <el-option label="成品" :value="1" />
            <el-option label="配件" :value="2" />
          </el-select>

          <el-input
            v-model.trim="getGoodListParam.keyword"
            placeholder="请输入关键字"
            style="width: 160px"
            clearable
            @keyup.enter="getList"
            @clear="getList"
          />

          <h-button type="primary" @click="getList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </h-button>

          <h-button @click="onResetClick">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </h-button>

          <h-button type="primary" :loading="getGoodBomChildListLoading" @click="onBomQueryClick">
            <el-icon>
              <Search />
            </el-icon>
            BOM查询
          </h-button>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          ref="tableInstance"
          :border="true"
          :stripe="true"
          height="100%"
          :data="goodList"
          @selection-change="handleTableSelectionChange"
        >
          <!-- 选择 -->
          <el-table-column type="selection" width="50" :align="'center'" fixed="left" />

          <!-- 序号 -->
          <el-table-column type="index" label="序号" width="50" :align="'center'" fixed="left" />

          <!-- 产品编号 -->
          <el-table-column show-overflow-tooltip label="产品编号" prop="code" width="140" />

          <!-- 产品名称 -->
          <el-table-column show-overflow-tooltip label="名称" prop="name" min-width="140" />

          <!-- 产品规格 -->
          <el-table-column show-overflow-tooltip label="规格" prop="specName" width="140" />

          <!-- 产品分类 -->
          <el-table-column show-overflow-tooltip label="分类" prop="type" width="100" />

          <!-- 产品规格 -->
          <el-table-column show-overflow-tooltip label="单价" prop="price" width="140">
            <template #default="{ row }"> ￥{{ (row.price || 0).toFixed(2) }} </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column label="创建时间" prop="createTime" width="128" />

          <!-- 更新时间 -->
          <el-table-column label="更新时间" prop="updateTime" width="128" />
        </el-table>
      </div>

      <div class="footer">
        <Pagination
          ref="paginationInstance"
          :list_total="goodListTotal"
          @current-change="getList"
          @size-change="getList"
        />
      </div>
    </div>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="onCancelClick">取消</h-button>
    </template>

    <bom-select-modal
      v-model="bomSelectModalVisible"
      :good-id="selection[0] ? selection[0].id : ''"
      :good-selection="props.goodSelection"
      @update="handleBomSelectModalUpdate"
    />
  </h-drawer>
</template>

<style scoped lang="scss">
  .good-select-modal {
    width: 100%;
    height: 99%;
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 14px;
        padding-left: 4px;
        border-left: 3px solid #007cff;
        height: fit-content;
        font-weight: bold;
      }

      .search {
        display: flex;
        column-gap: 8px;
      }
    }

    .table-wrapper {
      max-height: calc(100% - 28px - 8px - 28px - 8px);
    }

    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
